package com.crl.module.loaders
{
	import com.crl.module.loaders.workers.BitmapWorker;
	import com.crl.module.loaders.workers.Worker;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	
	/**
	 * 保证用一个worker 就完成所有加载过程，必须要是统一的类型才可以的,如：.jpg,xx.png,xx.gif 等图片格式;
	 * @author crl
	 * 
	 */	
	public class QueueSingleWorker extends Worker implements IQueueWorker
	{
		private var paths:Vector.<String>;
		private var pointer:int;
		private var total:int;
		
		
		/**
		 * 
		 * @param paths 资源地址列表.如果数组中有部份数据为空，应事先清理掉,此处不做具体的处理;
		 * @param loader
		 * 
		 */		
		public function QueueSingleWorker(paths:Vector.<String>,loader:Worker=null)
		{
			if(loader){
				loader=new BitmapWorker();
			}
			this.paths=paths;
			this.total=paths.length;
			
			this.loader=loader;
		}
		
		public function get itemTotal():int{
			return this.total;
		} 
		public function get itemLoaded():int{
			return this.pointer;
		}
		
		override public function start() : void{
			_data=[];
			
			pointer=-1;
			loadNext();
		}
		
		public function loadNext():void{

			if(pointer<this.paths.length-1){
				pointer++;
				
				var path:String=this.paths[pointer];
				request=new URLRequest(path);
				
				var w:Worker=loader;
				w.addEventListener(Event.COMPLETE,completeHandler);
				w.addEventListener(ErrorEvent.ERROR,errorHandler);
				
				w.load(request,true);
			}else{
				
				var w:Worker=loader;
				w.removeEventListener(Event.COMPLETE,completeHandler);
				w.removeEventListener(ErrorEvent.ERROR,errorHandler);
				
				this.onComplete(new Event(Event.COMPLETE));
			}
		}
		
		private function errorHandler(event:Event):void{
			this.loadNext();
		}
		private function completeHandler(event:Event):void{
			var w:Worker=event.target as Worker;
			//不用删除侦听;
			
			this.dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS,event.bubbles,event.cancelable,this.pointer,this.total);
			
			_data.push(w.data);
			this.loadNext();
		}
	}
}